<template >
  <div>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card>
          <el-row :gutter="20" type="flex" justify="center">
            <el-upload
              class="upload-demo cus-upload"
              :http-request="uploadFile"
              drag
              action="https://jsonplaceholder.typicode.com/posts/"
              multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip" style="color: crimson;font-size:24px">上传nii文件</div>
            </el-upload>
          </el-row>
          <el-row :gutter="20" type="flex" justify="left" >
              <el-col :span="24" >
                <el-card>
                  <el-col :span="6">
                    <el-button
                      type="danger"
                      plain
                      icon="el-icon-delete"
                      size="mini"
                      :disabled="this.isqueue||this.isloading||this.isrun"
                      @click="handleBatchDelete"
                    >批量删除</el-button>
                  </el-col>
                  <el-col :span="6"><div class="grid-content ">选择模态</div></el-col>
                  <el-col :span="12">
                    <el-radio v-model="inputype" label="1" :disabled=this.isqueue||this.isloading||this.isrun>T1</el-radio>
                    <el-radio v-model="inputype" label="2" :disabled=this.isqueue||this.isloading||this.isrun>DWI</el-radio>
                  </el-col>
                </el-card>
              </el-col>
          </el-row>
          <el-row :gutter="20" type="flex" justify="center">
            <el-table
              :data="userList"
              style="width: 100%" @selection-change="handleSelectionChange">
              <el-table-column
                type="selection"
                width="55"
                :selectable="canSelect">
              </el-table-column>
              <el-table-column
                prop="subname"
                label="被试名"
                align="center"
                width="100">
              </el-table-column>
              <el-table-column
                prop="status"
                align="center"
                label="状态"
                width="250"
              >
                <template slot-scope="scope">
                  <el-input placeholder=""
                            readonly="true"
                            v-model="scope.row.status"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.row)"
                    :disabled="canhandle(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-card>
        <el-card>
          <el-row :gutter="20" type="flex" justify="center">
            <el-button class="center" type="primary" @click="caculate" :disabled=this.isqueue||this.isloading||this.isrun>计算</el-button>
          </el-row>
        </el-card>
      </el-col>


      <el-col :span="12">
        <el-card>
          <el-row :gutter="20" type="flex" justify="center">
            <el-table
              :data="userList"
              style="width: 100%" @selection-change="handleSelectionChange" >
              <el-table-column
                type="selection"
                width="55"
                :selectable="canSelectnostatus">
              </el-table-column>
              <el-table-column
                prop="subname"
                label="被试名"
                align="center"
                width="100">
              </el-table-column>
              <el-table-column
                prop="endTime"
                label="计算日期"
                align="center"
                width="150">
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="common"
                    @click="handlewatch(scope.row)">查看</el-button>
                  <el-button
                    size="mini"
                    type="common"
                    @click="handleDownload(scope.row)"
                    :disabled="!canhandle(scope.row)">下载结果报告</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-card>
        <el-card>
          <el-row :gutter="20" type="flex" justify="center">
            <el-button class="center" type="primary" @click="caculate" :disabled="true">下载(维护逻辑中)</el-button>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>

</template>
<script>
import axios from "axios";
import { saveAs } from 'file-saver';
import Vue from 'vue';
import { batchDeleteSubject, Delete, getaskId, getuserlist, progressload, queueload, upload ,run,download} from '@/api/istroke/istroke'



export default {
  created() {
    this.getaskidanduserlist();
  },
  watch: {
    isqueue(newwel){
      if(newwel==true){
        this.queueloader();
      }
    },
    isloading(newwel) {
      if(newwel){
        this.runloading();
        this.progressloader();
      }else{
        this.runloading().close();
      }
    }
  },
  computed:{
  },


  data() {
    return {
      isloading:false,
      isqueue:false,
      numwait:0,
      isrun:false,
      isover:false,
      taskId:undefined,
      files: null,
      // 获取用户列表的参数对象
      userList: [],
      ids:[],
      idsdownload:[],
      countdown:false ,// 初始倒计时时间


      inputype:null,

    }
  },
  methods: {
    getaskidanduserlist(){
      getaskId().then(res => {
        this.isrun = res.isrun;
        this.isover = res.isover;
        this.taskId = res.taskId;
        this.isqueue = res.isqueue;
        this.numwait = res.numwait;
        this.isloading = res.isloading;
        let p2 = {AllTaskId:res.taskId}
        getuserlist(p2).then(res2=>{
          this.userList=res2.userList;
          this.countdown = res2.countdown;
        })
        if(res.isqueue==true)
          this.queueloader();
        if(res.isloading==true){
          this.runloading();
          this.progressloader();
        }
        if(res.isrun==true)
          this.progressloader();
      })
    },
    queueloader(){
      let quetimer = setInterval(() => {
        let p = {allTaskId: this.taskId}
        queueload(p).then(res=>{
          this.isrun = res.isrun;
          this.isover = res.isover;
          this.isqueue = res.isqueue;
          this.numwait = res.numwait;
          this.isloading = res.isloading;
          if(res.isloading==true){
            clearInterval(quetimer);
          }
        }).catch(error=>{
          console.log(error)
        })
      }, 10000);
    },
    runloading(){
      const loading = this.$loading({
        lock: true,
        fullScreen: true,
        text: "运行阶段初始化准备中，此步骤准备时间比较久，请您稍安勿躁",
        background: "rgba(255,255,255,0.99)"
      })
      return loading;
    },
    progressloader(){
      let timer = setInterval(() => {
        let p = {allTaskId: this.taskId}
        progressload(p).then(res=>{
          this.isrun = res.isrun;
          this.isover = res.isover;
          this.isqueue = res.isqueue;
          this.numwait = res.numwait;
          this.isloading = res.isloading;
          this.userList = res.userList;
          this.countdown = res.countdown;
          if(res.isover==true){
            clearInterval(timer);
          }
        }).catch(error=>{
          console.log(error)
        })
      }, 5000);
    },
    uploadLoading(){
      const loading = this.$loading({         // 声明一个loading对象
        lock: true,
        fullScreen: true,
        text: "上传文件中，请您耐心等待",
        background: "rgba(255,255,255,0.99)"
      })
      return loading;
    },



    handleSelectionChange(val) {
      this.ids = val.map(item => item.id);
    },
    handleDelete(row){
      this.$modal.confirm('是否删除？').then(() =>  {
        let p = {id:row.id,taskId:this.taskId,subname:row.subname}
        Delete(p).then(res=>{
          this.getaskidanduserlist();
          this.$modal.msgSuccess("删除成功");
        })
      })
    },
    handleBatchDelete() {
      if(this.ids.length!=0){
        this.$modal.confirm('是否批量删除数据项？').then(() =>  {
          let p = {ids: this.ids,taskId:this.taskId}
          batchDeleteSubject(p).then(res => {
            this.getaskidanduserlist();
            this.$modal.msgSuccess("删除成功");
          })
        })
      }
      else {
        this.$notify.error({
          title: '错误',
          message: '请至少选择一个被试'
        });
      }
    },

    uploadFile(file) {
      const pageLoading = this.uploadLoading();
      console.log(file.file)
      const formData = new FormData();
      formData.append('file', file.file); // 将文件添加到FormData对象中
      formData.append('taskId',this.taskId)
      console.log(formData)
      upload(formData).then(res => {
        console.log(res)
        if(res.success=="上传成功"){
          let p2 = {AllTaskId:this.taskId}
          getuserlist(p2).then(res2=>{
            this.userList=res2.userList;
            pageLoading.close()
          })
        }
        else{
          pageLoading.close()
          this.$alert(res.error, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },


    async caculate(){
      if(this.userList.length==0||this.userList==null)
        this.$alert('请上传计算需要的文件才能运行', '注意', {
          confirmButtonText: '确定',
        });
      else {
        try{
          await new Promise(resolve => setTimeout(resolve, 1000));

          let p = {'allTaskId':this.taskId,'ids':this.ids,'inputType':this.inputype};
          run(p).then(res => {
            if(res.error==1){
              this.$notify.error({
                title: '错误',
                message: '请至少选择一个被试'
              });
            }
            else if(res.error==2){
              this.$notify.error({
                title: '错误',
                message: '请选择模态'
              });
            }
            else{
              this.isrun = res.isrun;
              this.isover = res.isover;
              this.isquque = res.isqueue;
              this.numwait = res.numwait;
              this.isloading = res.isloading;
            }
          }).catch(error=>{
            console.log(error)
          })

        }catch (error){
          console.error(error);
        }
      }

    },


    handleDownload(row){
      console.log(row)
      let taskId = this.taskId
      let subname = row.subname
      download({ taskId ,subname}).then(res=>{
        const url = window.URL.createObjectURL(new Blob([res]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', subname+"_report.docx");
        document.body.appendChild(link);
        link.click();
      })
    },
    canSelect(row){
      if(this.isquque||this.isloading||this.isrun)
        return false
      else {
        return !row.isover
      }
    },
    canSelectnostatus(row){
      return row.isover
    },
    canhandle(row) {
      if (this.isquque||this.isloading||this.isrun)
        return true
      else{
        if(row.isover)
          return true
        else
          return false
      }
    },


  }
}

</script>
<style>
.el-upload__tip {
  line-height: 1.2;
  text-align:center;
}
.div
{background-color: #588ed3;}
</style>
